package com.ruoyi.core.service.impl;

import java.util.*;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.core.domain.Codes;
import com.ruoyi.core.domain.DeleteCode;
import com.ruoyi.core.domain.vo.GiftCardVo;
import com.ruoyi.core.mapper.CodesMapper;
import com.ruoyi.core.mapper.DeleteCodeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.core.mapper.GiftCardMapper;
import com.ruoyi.core.domain.GiftCard;
import com.ruoyi.core.service.IGiftCardService;
import com.ruoyi.common.core.text.Convert;

/**
 * 礼品卡Service业务层处理
 * 
 * @author lgc
 * @date 2020-08-08
 */
@Service
public class GiftCardServiceImpl implements IGiftCardService 
{
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private GiftCardMapper giftCardMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private CodesMapper codesMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private DeleteCodeMapper deleteCodeMapper;

    Logger logger =  LoggerFactory.getLogger(this.getClass());
    /**
     * 查询礼品卡
     * 
     * @param giftCardId 礼品卡ID
     * @return 礼品卡
     */
    @Override
    public GiftCard selectGiftCardById(Long giftCardId)
    {
        return giftCardMapper.selectGiftCardById(giftCardId);
    }

    /**
     * 查询礼品卡列表
     * 
     * @param giftCard 礼品卡
     * @return 礼品卡
     */
    @Override
    public List<GiftCardVo> selectGiftCardList(GiftCard giftCard)
    {
        return giftCardMapper.selectGiftCardList(giftCard);
    }

    /**
     * 新增礼品卡
     * 
     * @param giftCard 礼品卡
     * @return 结果
     */
    @Override
    public int insertGiftCard(GiftCard giftCard,Long startCode,Long endCode,Long userId)
    {
        Codes codes = null;
        giftCard.setCreatedBy(userId);
        giftCard.setLastUpdatedBy(userId);
        giftCard.setLastUpdatedDate(Calendar.getInstance().getTime());
        giftCard.setCreatedDate(Calendar.getInstance().getTime());

        //按序列号添加多条礼品卡
        for (Long i = startCode; i <= endCode; i++) {
             codes = codesMapper.selectCodesBy(i,userId);
            if (codes==null){
                throw new BusinessException(i + "序列号对应的码不存在");
            }
            Integer count = giftCardMapper.selectCount(codes.getCode(),userId);
            if (count!=0){
                logger.warn("该序号{}对应码已存在",i);
                continue;
            }
            giftCard.setCode(codes.getCode());
            giftCard.setFwCode(codes.getFwCode());
            if (giftCardMapper.insertGiftCard(giftCard) != 1) {
                throw new BusinessException(i + "序列号绑码失败");
            }
        }
        return 1;
    }

    /**
     * 修改礼品卡
     * 
     * @param giftCard 礼品卡
     * @return 结果
     */
    @Override
    public int updateGiftCard(GiftCard giftCard)
    {
        return giftCardMapper.updateGiftCard(giftCard);
    }

    /**
     * 删除礼品卡对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteGiftCardByIds(String ids)
    {
        return giftCardMapper.deleteGiftCardByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除礼品卡信息
     * 
     * @param giftCardId 礼品卡ID
     * @return 结果
     */
    @Override
    public int deleteGiftCardById(Long giftCardId)
    {
        return giftCardMapper.deleteGiftCardById(giftCardId);
    }

    /**
     * 校验该序列号的码已被绑定
     *
     * @param code 码
     * @return 结果
     */
    @Override
    public Boolean checkCode(String code,Long userId) {
        Boolean result = false;
        Integer count = giftCardMapper.selectCount(code,userId);
        if(count.equals(0)){
            result = true; //没有该用户的相关码
        }
        return result;
    }

    /**
     * 更新卡劵状态，并把剔除数据添加到剔除表中去
     *
     * @param ids 码
     * @return 结果
     */
    @Override
    public int updateStatesByIds(String ids,Long userId) {
        Long[] idArray = Convert.toLongArray(ids);
        for (int i = 0; i < idArray.length; i++) {
            GiftCardVo giftCardVo = giftCardMapper.selectGiftCardByIndex(idArray[i],userId);
            if(giftCardVo.getIsUsed()==1||giftCardVo.getIsDeleted()==1){
                throw new BusinessException("不可剔除已使用的"+giftCardVo.getIndex()+"序列号或已剔除的礼品卡");
            }
        }
        if (giftCardMapper.updateStatesByIds(idArray,userId)<=0){
            throw new BusinessException("批量剔除错误！");
        }
        //获取所有数据封装到扩展实体类
        List<GiftCardVo> giftCardVos = giftCardMapper.selectGiftCardByIds(idArray,userId);
        //将数据添加到剔除表
        for (GiftCardVo giftCardVo : giftCardVos) {
            saveDeleteCode(userId, giftCardVo);
        }
        return 1;
    }

    //添加数据到剔除表
    private void saveDeleteCode(Long userId, GiftCardVo giftCardVo) {
        DeleteCode deleteCode = new DeleteCode();
//            BeanUtils.copyProperties(giftCardVo,deleteCode);
        deleteCode.setCreatedDate(Calendar.getInstance().getTime());
        deleteCode.setCreatedBy(userId);
        deleteCode.setUserId(userId);
        deleteCode.setDeleteSerialCode(giftCardVo.getIndex().longValue());
        deleteCode.setFwCode(giftCardVo.getFwCode());
        deleteCode.setProductId(giftCardVo.getProductId().longValue());
        deleteCode.setLogisticsCode(giftCardVo.getCode());
        if (deleteCodeMapper.insertDeleteCode(deleteCode)!=1){
            throw new BusinessException("添加剔除表错误");
        }
    }

    @Override
    public int updateStatesBy(Long startCode, Long endCode, Long userId) {
        //检测是否有已使用的
        for (Long i = startCode; i <= endCode; i++) {
            GiftCardVo giftCardVo = giftCardMapper.selectGiftCardByIndex(i,userId);
           if(giftCardVo!=null&&giftCardVo.getIsUsed()==1){
              throw new BusinessException("不可剔除已使用的"+i+"序列号");
           }
        }

        for (Long i = startCode; i <= endCode; i++) {
            DeleteCode deleteCode = deleteCodeMapper.selectDeleteCodeById(i,userId);
            //如果已经存在不重复添加
            if (deleteCode==null){
                GiftCardVo giftCardVo = giftCardMapper.selectGiftCardByIndex(i,userId);
                Optional.ofNullable(giftCardVo).ifPresent((g) -> {
                    saveDeleteCode(userId,g);
                });
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("startCode",startCode);
        map.put("endCode",endCode);
        map.put("userId",userId);
        if ( giftCardMapper.updateStatesByCodes(map)<1){
            throw new BusinessException("修改剔除状态错误！");
        }
        return 1;
    }

    @Override
    public Long testCode(String code, String password,Long userId) {
        Boolean exist = checkCode(code,userId);
        if (exist){
            throw new BusinessException("该提货码不存在，谨防假冒");
        }
        GiftCard giftCard = new GiftCard();
        giftCard.setCode(code);giftCard.setFwCode(password);giftCard.setIsDeleted(0L);giftCard.setIsUsed(0);
        List<GiftCardVo> giftCardVos = selectGiftCardList(giftCard);
        if (giftCardVos.isEmpty()){
            throw new BusinessException("该提货码的密码错误或已被使用");
        }
        GiftCardVo giftCardVo = giftCardVos.get(0);

        //超时无法兑换
        Date date = new Date();
        if (date.before(giftCardVo.getStartDate()) || date.after(giftCardVo.getEndDate())) {
            throw new BusinessException("该提货码已过期");
        }

        return giftCardVos.get(0).getGiftCardId();
    }

    @Override
    public void checkCodes( String code,Long userId) {
        Boolean exist = checkCode(code,userId);
        if (exist){
            throw new BusinessException("该用户的提货码不存在，谨防假冒");
        }
    }
}
